﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using Local.Service;
using NReader.Model;
using NReader.Model.RAS;
using Windows.Storage;

namespace NReader.Service
{
    public class GlobalService
    {
        private const int HotFlag = 2002;

        private const int CommendFlag = 2003;

        private const int SizeUpdateCount = 18;

        private const int SizeHistoryCount = 9;

        private const int CompleteFlag = 2005;

        /// <summary>
        /// 书架最大上限
        /// </summary>
        private const int Maxsizebookcase = 20;

        public static GlobalService _globalService;

        public static GlobalService Instance()
        {
            return _globalService ?? (_globalService = new GlobalService());
        }

        public async Task<List<GroupInfoList<object>>> GetIndexGroupList()
        {
            var client = new RemoteArticleServiceClient();
            //点击排行榜
            //IList<ArticleInfo> rankList = await client.GetGroupListAsync(RankFlag);
            //热点排行榜
            IList<ArticleInfo> hotList = await client.GetGroupListAsync(HotFlag);
            //推荐排行榜
            IList<ArticleInfo> commendList = await client.GetGroupListAsync(CommendFlag);
            //全本排行榜
            IList<ArticleInfo> completeList = await client.GetGroupListAsync(CompleteFlag);
            //最新更新
            IList<ArticleInfo> updateList = await client.GetUpdateListAsync(SizeUpdateCount);
            var groups = new List<GroupInfoList<object>>();
            var historyList =
                await Local.Service.LocalSqliteService.Instance().GetHistoryList(SizeHistoryCount);
            if (historyList != null)
            {
                AddArticleToGroup(historyList, ref groups);
            }
            //AddArticleToGroup(rankList, ref groups);
            AddArticleToGroup(completeList, ref groups);
            AddArticleToGroup(hotList, ref groups);
            AddArticleToGroup(commendList, ref groups);
            AddArticleToGroup(updateList, ref groups);

            return groups;
        }

        public void AddArticleToGroup(IList<ArticleInfo> list, ref List<GroupInfoList<object>> groups)
        {
            var query = from item in list
                        //orderby item.lastupdate
                        group item by item.GroupName
                        into g
                        select new {GroupName = g.Key, Items = g};
            foreach (var g in query)
            {
                var info = new GroupInfoList<object> {Key = g.GroupName};
                foreach (var item in g.Items)
                {
                    info.Add(item);
                }
                groups.Add(info);
            }
        }

        public async Task<List<GroupInfoList<object>>> GetIndexGroupListFromLocal()
        {
            var groups = new List<GroupInfoList<object>>();
            var historyList =
                await Local.Service.LocalSqliteService.Instance().GetHistoryList(SizeHistoryCount);
            if (historyList != null)
            {
                AddArticleToGroup(historyList, ref groups);
            }
            var list = await Local.Service.LocalXmlService.GetIndexGroup();
            AddArticleToGroup(list, ref groups);
            return groups;
        }

        public async Task<IList<SysWebInfo>> GetSysWebInfosFromLocal()
        {
            return await Local.Service.LocalXmlService.GetSysWebInfos();
        }

        public async Task SaveIndexGroupList(List<GroupInfoList<object>> groupList)
        {
            var list =
                (from @group in groupList where !@group.Key.Equals("浏览记录") from o in @group select o as ArticleInfo).
                    ToList();
            await Local.Service.LocalXmlService.SaveIndexGroup(list);
        }

        public async Task SaveSysWebInfos(IList<SysWebInfo> list)
        {
            await Local.Service.LocalXmlService.SaveSysWebInfo(list);
        }

        public async Task<IList<SysWebInfo>> GetSysWebList()
        {
            var client = new RemoteArticleServiceClient();
            return await client.GetWebInfoListAsync();
        }

        public async Task<SysWebInfo> GetSysWebInfoFromLocal(string webflag)
        {
            return await Local.Service.LocalXmlService.GetSysWebInfo(webflag);
        }

        /// <summary>
        /// 获取书架及阅读历史
        /// </summary>
        /// <returns></returns>
        public async Task<ObservableCollection<ArticleGroup>> GetBookCaseAndHistory(int bookcaseId)
        {
            return null;
            //var history = await Local.Service.LocalSqliteService.Instance().GetHistoryList(SizeHistoryCount);
            //var historyList = new ObservableCollection<ArticleInfo>();
            //var lastday = "";
            //var tmpday = "";
            ////计算日期
            //foreach (var articleInfo in history)
            //{
            //    if (articleInfo.online.Equals(0))
            //        articleInfo.intro = string.Format("{0}%", (articleInfo.historyprogress * 100).ToString("N2"));
            //    else
            //    {
            //        //在线书籍不显示进度
            //        articleInfo.intro = string.Empty;
            //    }
            //    articleInfo.keywords = GetUpdatetime(articleInfo.updatetime, out tmpday);
            //    articleInfo.updatetime = tmpday; //展示在界面代表日期
            //    if (!lastday.Equals(tmpday))
            //    {
            //        lastday = tmpday;
            //    }
            //    else
            //    {
            //        articleInfo.updatetime = string.Empty;
            //        articleInfo.keywords = string.Empty;
            //    }
            //    historyList.Add(articleInfo);
            //}

            //var bookcases = await Local.Service.LocalSqliteService.Instance().GetBookcases();
            //var caselist = new ObservableCollection<ArticleInfo>();
            //foreach (var bookcaseInfo in bookcases)
            //{
            //    //加入书架信息
            //    caselist.Add(new ArticleInfo()
            //    {
            //        articlename = bookcaseInfo.casename,
            //        articleid = bookcaseInfo.id,
            //        intro = bookcaseInfo.remark,
            //        author = string.Format("{0}", bookcaseInfo.total),//包含的书籍数,界面绑定该字段
            //        display = bookcaseId == bookcaseInfo.id ? 1 : 0, //用display字段指示是否为当前选中的书架
            //        GroupName = "nav"
            //    });
            //}
            //var list = new ObservableCollection<ArticleGroup>
            //               {
            //                   new ArticleGroup() {GroupTitle = "最近阅读", Items = historyList},
            //                   new ArticleGroup() {GroupTitle = "我的书架", Items = caselist},
            //                   new ArticleGroup() //默认显示第一个书架
            //                       {
            //                           GroupTitle = "",
            //                           Items =
            //                               await LocalSqliteService.Instance().GetBookStore(bookcaseId)
            //                       }
            //               };
            //return list;
        }

        /// <summary>
        /// 获取阅读历史
        /// </summary>
        /// <returns></returns>
        public async Task<IList<ArticleInfo>> GetHistory()
        {
            return await Local.Service.LocalSqliteService.Instance().GetHistoryList(SizeHistoryCount);
        }

        public async Task<IList<ArticleInfo>> GetBookcases(int bookcaseId)
        {
            return await LocalSqliteService.Instance().GetBookStore(bookcaseId);
        }

        ///// <summary>
        ///// 获取所有书架分组
        ///// </summary>
        ///// <returns></returns>
        //public async Task<ObservableCollection<ArticleGroup>> GetBookcaseGroup()
        //{
        //    var bookcases = await Local.Service.LocalSqliteService.Instance().GetBookcases();
        //    var list = new ObservableCollection<ArticleGroup>();
        //    foreach (var bookcaseInfo in bookcases)
        //    {
        //        var group = new ArticleGroup() {};
        //        group.GroupTitle = bookcaseInfo.casename;
        //        group.Items = await Local.Service.LocalSqliteService.Instance().GetBookStore(bookcaseInfo.id);
        //        list.Add(group);
        //    }
        //    return list;
        //}

        /// <summary>
        /// 获取书架列表，包含书架数量
        /// </summary>
        /// <returns></returns>
        public async Task<IList<BookcaseInfo>> GetBookCases()
        {
            var list = new List<BookcaseInfo>();
            var bookcase = new BookcaseInfo { casename = "最近阅读", id = 0 };
            var histtory =await GetHistory();
            bookcase.total = histtory.Count;
            list.Add(bookcase);

            var bookcases = await LocalSqliteService.Instance().GetBookcases();
            list.AddRange(bookcases);
            return list;
        }

        /// <summary>
        /// 获取日期显示信息
        /// </summary>
        /// <param name="datetime"></param>
        /// <param name="days"></param>
        /// <returns></returns>
        private string GetUpdatetime(string datetime, out string days)
        {
            days = "";
            if (DateTime.Now.ToString("yyyyMMdd").Equals(datetime.Substring(0, 8)))
            {
                days = string.Format("{0}/{1}月", datetime.Substring(6, 2), datetime.Substring(4, 2));
                return "今天";
            }
            int now = int.Parse(DateTime.Now.ToString("yyyyMMdd"));
            int ago = int.Parse(datetime.Substring(0, 8));
            int remain = now - ago;
            if (remain == 1)
            {
                days = string.Format("{0}/{1}月", datetime.Substring(6, 2), datetime.Substring(4, 2));
                return "昨天";
            }
            else if (remain > 1 && remain <= 7)
            {
                return "本周";
            }
            else
            {
                var date = DateTime.Now.AddDays(-7).ToString("yyyyMMdd");
                days = string.Format("{0}/{1}前", date.Substring(6, 2), date.Substring(4, 2));
                return "更早";
            }
        }

        #region 设置

        public async Task SaveSetting(SettingInfo setting)
        {
            Local.Service.LocalXmlService.SaveSetting(setting);
        }

        public async Task<SettingInfo> GetSetting()
        {
            string path = Path.Combine(ApplicationData.Current.LocalFolder.Path, "global", "setting");
            if (!Utils.FileExists(path))
            {
                var setting = new SettingInfo
                                  {
                                      Background = 3,
                                      Encoding = "gb2312",
                                      FontFamily = "Microsoft YaHei",
                                      FontSize = 18,
                                      FontColor = "black"
                                  };
                Local.Service.LocalXmlService.SaveSetting(setting);
                return setting;
            }
            return await Local.Service.LocalXmlService.GetSetting();
        }

        #endregion
    }

    public class GroupInfoList<T> : List<object>
    {
        public object Key { get; set; }

        public new IEnumerator<object> GetEnumerator()
        {
            return (System.Collections.Generic.IEnumerator<object>) base.GetEnumerator();
        }
    }

    /// <summary>
    /// 书籍组
    /// </summary>
    public class ArticleGroup
    {
        public ArticleGroup()
        {
        }

        public string GroupTitle { get; set; }

        public ObservableCollection<ArticleInfo> Items { get; set; }
    }
}
